package com.itheima.service.impl;

import com.itheima.exception.DeptAlreadyExistsException;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @Override
    public List<Dept> list() {
        return deptMapper.selectList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class,
            propagation = Propagation.REQUIRES_NEW)
    public void removeById(Integer id) {
        // 删除部门
        deptMapper.deleteById(id);
    }

    @Override
    public void add(Dept dept) {
        // 在这里校验部门已经存在
        // 抛出异常
        Integer count = deptMapper.selectCountByName(dept.getName());
        if (count > 0) {
            throw new DeptAlreadyExistsException();
        }
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }
}
